<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-if="flag">
      <el-form-item label="全局操作:" prop="global" v-if="viewType=='1'">
        <el-checkbox-group v-model="form.global">
          <div class="item">
            <el-checkbox label="add">
              新增
            </el-checkbox>
            <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.addRole" placeholder="操作权限">
              <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
            </el-select>
          </div>
          <div class="item">
            <el-checkbox label="batchDelete">
              批量删除
            </el-checkbox>
            <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.batchDeleteRole" placeholder="操作权限">
              <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
            </el-select>
          </div>
          <div class="item">
              <el-checkbox label="import">
                导入
              </el-checkbox>
              <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.importRole" placeholder="操作权限">
                <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
              </el-select>
          </div>
          <div class="item">
              <el-checkbox label="export">
                导出
              </el-checkbox>
              <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.exportRole" placeholder="操作权限">
                <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
              </el-select>
          </div>
          <div class="item">
              <el-checkbox label="exportAll">
                全量导出
              </el-checkbox>
              <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.exportAllRole" placeholder="操作权限">
                <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
              </el-select>
          </div>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="数据操作:" prop="row" v-if="viewType=='1'">
        <el-checkbox-group v-model="form.row">
          <div class="item">
            <el-checkbox label="edit">
              编辑
            </el-checkbox>
            <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.editRole" placeholder="操作权限">
              <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
            </el-select>
          </div>
          <div class="item">
            <el-checkbox label="detail">
              详情
            </el-checkbox>
            <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.detailRole" placeholder="操作权限">
              <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
            </el-select>
          </div>
          <div class="item">
            <el-checkbox label="delete">
              删除
            </el-checkbox>
            <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.deleteRole" placeholder="操作权限">
              <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
            </el-select>
          </div>
          <div class="item">
            <el-checkbox label="select">
              选择
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="增改详情表单:" v-if="getAddEditKey()">
        {{getAddEditKey()}}
        <el-button type="text" style="margin-left: 20px;" @click="setForm(true)">初始化配置</el-button>
        <el-button type="text" style="margin-left: 20px;" @click="setForm(false)">线上配置</el-button>
      </el-form-item>
      <el-form-item label="编辑权限:" v-if="viewType=='2'&&getAddEditKey()">
        <el-select size="mini" clearable multiple style="width: 400px;" v-model="form.addRole" placeholder="操作权限">
          <el-option v-for="item in listRole" :key="item.roleKey" :label="item.roleName" :value="item.roleKey"/>
        </el-select>
      </el-form-item>

      <el-form-item label="导入功能:" v-if="showImportKey&&imports" prop="import">
        <el-select v-model="form.import" clearable multiple placeholder="请选择" style="width: 300px;">
          <el-option v-for="item,index in imports" :key="index"
          :label="item.configName" :value="item.configKey"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    listTable
  } from "@/api/tool/importExport";
  export default {
    name: 'action',
    components: {},
    props: {
      listRole: {
        type: Array,
        defulat: () => []
      },
      viewKey: {
        type: String,
        defulat: ''
      },
      viewName: {
        type: String,
        defulat: ''
      },
      formKey: {
        type: String,
        defulat: ''
      },
      extraFormKeys: {
        type: Array,
        defulat: () => []
      },
      action: {
        type: Object,
        defulat: () => {}
      },
      primaryKeyFieldObj: {
        type: Object,
        defulat: () => {}
      },
      viewType: {
        type: [Number, String],
        defulat: '1'
      },
      refreshByDel: {
        type: Boolean,
        defulat: false
      },
    },
    computed:{
      showImportKey() {
        return this.viewKey && this.formKey && this.form.global.indexOf('import') > -1
      },
    },
    watch:{
      showImportKey(val){
        if(val&&!this.imports){
            listTable({pageNum: 1,pageSize: 999}).then(res=>{
                this.imports=res.rows.map(item=>{
                  this.importNames[item.configKey]=item.configName
                  item.configName=item.configName+`（${item.configKey}）`
                  return item
                })
            })
        }
      }
    },
    data() {
      return {
        flag:false,
        form: {
          global: [],
          row: [],
          addEdit: '',
          import: '',
          addRole:undefined,
          batchDeleteRole:undefined,
          importRole:undefined,
          exportRole:undefined,
          exportAllRole:undefined,
          editRole:undefined,
          detailRole:undefined,
          deleteRole:undefined,
        },
        rules:{
          import: [{
            required: true,
            message: '请选择导入功能',
            trigger: 'change'
          }],
        },
        imports: null,
        importNames: {}
      };
    },
    created() {
      setTimeout(() => {
        if (this.action) {
          Object.keys(this.action).forEach(key=>{
            this.form[key]=this.action[key]
          })
        }
        Object.keys(this.form).forEach(key=>{
          if(key.indexOf('Role')>-1){
            if(!this.form[key]){
              this.form[key]=this.listRole.map(item=>{
                return item.roleKey
              })
            }
          }
        })
        this.flag=true
      }, 1000)
    },
    methods: {
      submit() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            let form = JSON.parse(JSON.stringify(this.form))
            if (this.viewType == '2') {
              form.global = []
              form.row = ['addEdit']
            }
            form.addEdit = this.getAddEditKey()
            if(!this.showImportKey){
              form.import = ''
            }
            form.importNames=this.importNames
            this.$emit('setValue', {
              tabType: 'action',
              formData: form
            })
          }
        });
      },
      getAddEditKey() {
        let key=''
        if (this.viewKey && this.formKey && (this.viewType == '2' || this.form.global.indexOf('add') > -1 ||
        this.form.row.indexOf('edit') > -1|| this.form.row.indexOf('detail') > -1)) {
          key= this.viewKey + '_AddEdit'
        }
        return key
      },
      setForm(init) {
        let url='/tool/build?formKey='+this.getAddEditKey()+'&formTitle='+this.viewName+'_新增编辑',
            formEditorData = localStorage.getItem('formEditorData'),
            primaryKey=this.formKey+"__"+this.primaryKeyFieldObj[this.formKey];

        if (formEditorData) {
          formEditorData = JSON.parse(formEditorData)
        } else {
          formEditorData = {}
        }

        if(init){
            url+='&init=1'
            let formList=[this.formKey].concat(this.extraFormKeys),
                services=[],
                initApi={
                    "messages": {
                      "success": "查询成功",
                      "failed": "查询失败"
                    }
                  };
                if(this.viewType==1){
                  //列表模式
                 initApi.method="get"
                 initApi.url= "/openform/multiFormData/getData/"+this.viewKey+"/${"+primaryKey+"}"
                 initApi.sendOn="this."+primaryKey
                }else{
                  initApi.method="post"
                  initApi.url= "/openform/multiFormData/getDataByFilter/"+this.viewKey
                  initApi.sendOn="this.sysUser__user_id",
                  initApi.data={
                    "params": {
                      "user_id":  "${sysUser__user_id}",
                    }
                  }
                }


            formList.forEach(item=>{
               services.push({
                  "type": "service",
                  "name": item,
                  "className": "m-t",
                  "initFetchSchema": true,
                  "schemaApi": {
                    "url": `/openform/formDef/formDef/getControlByFormKeyAndBusinessId/${this.viewKey}/${item}`,
                    "cache": 60000,
                    "method": "get",
                    "payloadData":"${"+item+"||{}}",
                    "adaptor": "payload.data=api.payloadData;return payload"
                  },
                  "visibleOn": "${!"+(this.viewType==1?primaryKey:'sysUser__user_id')+"||"+item+"}",
                })
            })

            let schema ={
              "type": "page",
              "asideResizor": false,
              "regions": [
                "body"
              ],
              "body": {
                       "type": "form",
                       "id":this.getAddEditKey(),
                       "staticOn": "${isStatic}",
                       "disabledOn": "${isStatic}",
                       "actions": [
                         {
                           "type": "button",
                           "label": "提交",
                           "visibleOn": "${!isStatic}",
                           "level": "primary",
                           "onEvent": {
                             "click": {
                               "weight": 0,
                               "actions": [
                                 {
                                   "componentId": this.getAddEditKey(),
                                   "actionType": "validate"
                                 }
                               ]
                             }
                           }
                         }
                       ],
                       "title": "",
                       "body": services,
                       "mode": "horizontal",
                       "onEvent": {
                         "validateSucc": {
                           "weight": 0,
                           "actions": [{
                              "script": "if (context.props.store.data.form__submit_data) {\n  setTimeout(() => {\n    doAction({\n      actionType: 'setValue',\n      componentId: \""+this.getAddEditKey()+"\",\n      args: {\n        value: {\n          form__submit_data: ''\n        }\n      }\n    })\n  }, 100)\n} else {\n  let obj = {},\n    body = context.props.body,\n    children = context.props.store.children;\n  if (children && children.length) {\n    children.forEach((item, index) => {\n      if (item.data && !item.tmpValue && body[index].name) {\n        if (body[index].type == 'service') {\n          obj[body[index].name] = item.children[0].data\n        } else {\n          obj[body[index].name] = item.data\n        }\n      }\n    })\n  }\n  doAction({\n    actionType: 'setValue',\n    componentId: \""+this.getAddEditKey()+"\",\n    args: {\n      value: {\n        form__submit_data: obj\n      }\n    }\n  })\n  setTimeout(() => {\n    doAction({\n      actionType: 'submit',\n      componentId: \""+this.getAddEditKey()+"\"\n    })\n  },100)\n}\n\n\n",
                             "actionType": "custom"
                           }]
                         },
                         "submitSucc": {
                           "weight": 0,
                           "actions": [
                             {
                               "actionType": "closeDialog"
                             }
                           ]
                         }
                       },
                       initApi,
                       "reload":this.refreshByDel?("aside_tree__"+this.viewKey+"?tree_id=0"):("crud__"+this.viewKey),
                       "api": {
                         "url": "/openform/multiFormData/insertOrUpdate/"+this.viewKey,
                         "method": "post",
                         "messages": {
                           "success": "提交成功",
                           "failed": "提交失败"
                         },
                         "data":{
                           "&":"${form__submit_data}"
                         },
                         "sendOn": "${form__submit_data}"
                       },
                       "panelClassName": "no-border",
                       "style": {
                         "borderColor": "transparent",
                         "boxShadow": " 0px 0px 0px 0px transparent"
                       }
                     },
              "style": {
                "boxShadow": " 0px 0px 0px 0px transparent"
              },
              "pullRefresh": {
                "disabled": true
              },
              "cssVars": {
                "--Panel-footerBorderColor": "#fff"
              }
            }





            formEditorData[this.getAddEditKey()] = {
              formKey: this.getAddEditKey(),
              schema
            }
        }else{
          delete formEditorData[this.getAddEditKey()]
        }
        localStorage.setItem('formEditorData', JSON.stringify(formEditorData))
        this.$router.push(url)
      }
    }
  };
</script>
<style lang='scss' scoped>
  .item {
    width: 100%;
    float: left;
    margin-bottom: 20px;
    display: flex;
    .el-checkbox{
      width: 180px;
    }
  }
</style>
